#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include "download.h"
#include "../utils/log.h"

// 最大任务数
#define MAX_DOWNLOAD_TASKS 10

// 全局变量
static bool g_is_initialized = false;
static download_task_t *g_tasks[MAX_DOWNLOAD_TASKS] = {NULL};
static pthread_mutex_t g_tasks_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_t g_download_threads[MAX_DOWNLOAD_TASKS];
static download_progress_cb g_progress_callback = NULL;
static void *g_callback_user_data = NULL;
static int g_next_task_id = 1;

// 下载线程函数
static void *download_thread_func(void *arg)
{
    int task_id = *((int *)arg);
    free(arg);
    
    pthread_mutex_lock(&g_tasks_mutex);
    download_task_t *task = NULL;
    
    // 查找任务
    for (int i = 0; i < MAX_DOWNLOAD_TASKS; i++) {
        if (g_tasks[i] && g_tasks[i]->task_id == task_id) {
            task = g_tasks[i];
            break;
        }
    }
    
    if (!task) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载任务不存在: %d", task_id);
        return NULL;
    }
    
    task->status = DOWNLOAD_STATUS_DOWNLOADING;
    task->downloaded_size = 0;
    task->total_size = 1024 * 1024; // 模拟1MB的文件大小
    pthread_mutex_unlock(&g_tasks_mutex);
    
    LOG_INFO("开始下载任务: %d, 远程路径: %s, 本地路径: %s", 
             task_id, task->remote_path, task->local_path);
    
    // 模拟下载过程
    while (1) {
        pthread_mutex_lock(&g_tasks_mutex);
        
        // 检查任务状态
        if (task->status == DOWNLOAD_STATUS_PAUSED) {
            pthread_mutex_unlock(&g_tasks_mutex);
            LOG_INFO("下载任务暂停: %d", task_id);
            // 等待状态变化
            while (1) {
                usleep(100000);
                pthread_mutex_lock(&g_tasks_mutex);
                if (task->status != DOWNLOAD_STATUS_PAUSED) {
                    pthread_mutex_unlock(&g_tasks_mutex);
                    break;
                }
                pthread_mutex_unlock(&g_tasks_mutex);
            }
            pthread_mutex_lock(&g_tasks_mutex);
        }
        
        // 检查是否已取消
        if (task->status == DOWNLOAD_STATUS_IDLE) {
            pthread_mutex_unlock(&g_tasks_mutex);
            LOG_INFO("下载任务取消: %d", task_id);
            return NULL;
        }
        
        // 更新下载进度
        task->downloaded_size += 1024 * 100; // 每次下载100KB
        if (task->downloaded_size >= task->total_size) {
            task->downloaded_size = task->total_size;
            task->status = DOWNLOAD_STATUS_COMPLETED;
            pthread_mutex_unlock(&g_tasks_mutex);
            
            LOG_INFO("下载任务完成: %d", task_id);
            
            // 调用回调函数
            if (g_progress_callback) {
                g_progress_callback(task_id, task->downloaded_size, task->total_size, g_callback_user_data);
            }
            
            break;
        }
        
        pthread_mutex_unlock(&g_tasks_mutex);
        
        // 调用回调函数
        if (g_progress_callback) {
            g_progress_callback(task_id, task->downloaded_size, task->total_size, g_callback_user_data);
        }
        
        usleep(500000); // 模拟下载延迟
    }
    
    return NULL;
}

int download_init(void)
{
    pthread_mutex_lock(&g_tasks_mutex);
    
    if (g_is_initialized) {
        pthread_mutex_unlock(&g_tasks_mutex);
        return DOWNLOAD_SUCCESS;
    }
    
    // 初始化任务数组
    for (int i = 0; i < MAX_DOWNLOAD_TASKS; i++) {
        g_tasks[i] = NULL;
    }
    
    LOG_INFO("下载模块初始化成功");
    g_is_initialized = true;
    
    pthread_mutex_unlock(&g_tasks_mutex);
    return DOWNLOAD_SUCCESS;
}

void download_cleanup(void)
{
    pthread_mutex_lock(&g_tasks_mutex);
    
    if (!g_is_initialized) {
        pthread_mutex_unlock(&g_tasks_mutex);
        return;
    }
    
    // 清理所有任务
    for (int i = 0; i < MAX_DOWNLOAD_TASKS; i++) {
        if (g_tasks[i]) {
            free(g_tasks[i]);
            g_tasks[i] = NULL;
        }
    }
    
    LOG_INFO("下载模块清理完成");
    g_is_initialized = false;
    
    pthread_mutex_unlock(&g_tasks_mutex);
}

int download_create_task(enum download_type type, const char *remote_path, const char *local_path)
{
    pthread_mutex_lock(&g_tasks_mutex);
    
    if (!g_is_initialized) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载模块未初始化");
        return DOWNLOAD_ERROR_INIT;
    }
    
    // 检查参数
    if (!remote_path || !local_path) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("远程路径或本地路径为空");
        return DOWNLOAD_ERROR_FILE;
    }
    
    // 查找空闲任务槽
    int task_index = -1;
    for (int i = 0; i < MAX_DOWNLOAD_TASKS; i++) {
        if (g_tasks[i] == NULL) {
            task_index = i;
            break;
        }
    }
    
    if (task_index < 0) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载任务已满");
        return DOWNLOAD_ERROR_START;
    }
    
    // 创建新任务
    download_task_t *task = (download_task_t *)malloc(sizeof(download_task_t));
    if (!task) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("内存分配失败: %s", strerror(errno));
        return DOWNLOAD_ERROR_START;
    }
    
    // 初始化任务
    task->task_id = g_next_task_id++;
    task->type = type;
    strncpy(task->remote_path, remote_path, sizeof(task->remote_path) - 1);
    strncpy(task->local_path, local_path, sizeof(task->local_path) - 1);
    task->total_size = 0;
    task->downloaded_size = 0;
    task->status = DOWNLOAD_STATUS_IDLE;
    task->error_code = 0;
    
    g_tasks[task_index] = task;
    
    LOG_INFO("创建下载任务成功: %d", task->task_id);
    
    int task_id = task->task_id;
    pthread_mutex_unlock(&g_tasks_mutex);
    
    return task_id;
}

int download_start_task(int task_id)
{
    pthread_mutex_lock(&g_tasks_mutex);
    
    if (!g_is_initialized) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载模块未初始化");
        return DOWNLOAD_ERROR_INIT;
    }
    
    // 查找任务
    download_task_t *task = NULL;
    int task_index = -1;
    for (int i = 0; i < MAX_DOWNLOAD_TASKS; i++) {
        if (g_tasks[i] && g_tasks[i]->task_id == task_id) {
            task = g_tasks[i];
            task_index = i;
            break;
        }
    }
    
    if (!task) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载任务不存在: %d", task_id);
        return DOWNLOAD_ERROR_FILE;
    }
    
    // 检查任务状态
    if (task->status == DOWNLOAD_STATUS_DOWNLOADING) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_WARN("任务已经在下载中: %d", task_id);
        return DOWNLOAD_SUCCESS;
    }
    
    if (task->status == DOWNLOAD_STATUS_COMPLETED) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_WARN("任务已经完成: %d", task_id);
        return DOWNLOAD_SUCCESS;
    }
    
    // 创建下载线程
    int *id_ptr = (int *)malloc(sizeof(int));
    if (!id_ptr) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("内存分配失败: %s", strerror(errno));
        return DOWNLOAD_ERROR_START;
    }
    *id_ptr = task_id;
    
    pthread_mutex_unlock(&g_tasks_mutex);
    
    if (pthread_create(&g_download_threads[task_index], NULL, download_thread_func, id_ptr) != 0) {
        free(id_ptr);
        LOG_ERROR("创建下载线程失败: %s", strerror(errno));
        return DOWNLOAD_ERROR_START;
    }
    
    // 分离线程
    pthread_detach(g_download_threads[task_index]);
    
    return DOWNLOAD_SUCCESS;
}

int download_pause_task(int task_id)
{
    pthread_mutex_lock(&g_tasks_mutex);
    
    if (!g_is_initialized) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载模块未初始化");
        return DOWNLOAD_ERROR_INIT;
    }
    
    // 查找任务
    download_task_t *task = NULL;
    for (int i = 0; i < MAX_DOWNLOAD_TASKS; i++) {
        if (g_tasks[i] && g_tasks[i]->task_id == task_id) {
            task = g_tasks[i];
            break;
        }
    }
    
    if (!task) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载任务不存在: %d", task_id);
        return DOWNLOAD_ERROR_FILE;
    }
    
    if (task->status == DOWNLOAD_STATUS_DOWNLOADING) {
        task->status = DOWNLOAD_STATUS_PAUSED;
        LOG_INFO("暂停下载任务: %d", task_id);
    } else {
        LOG_WARN("任务不在下载状态，无法暂停: %d", task_id);
    }
    
    pthread_mutex_unlock(&g_tasks_mutex);
    return DOWNLOAD_SUCCESS;
}

int download_cancel_task(int task_id)
{
    pthread_mutex_lock(&g_tasks_mutex);
    
    if (!g_is_initialized) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载模块未初始化");
        return DOWNLOAD_ERROR_INIT;
    }
    
    // 查找任务
    download_task_t *task = NULL;
    int task_index = -1;
    for (int i = 0; i < MAX_DOWNLOAD_TASKS; i++) {
        if (g_tasks[i] && g_tasks[i]->task_id == task_id) {
            task = g_tasks[i];
            task_index = i;
            break;
        }
    }
    
    if (!task) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载任务不存在: %d", task_id);
        return DOWNLOAD_ERROR_FILE;
    }
    
    task->status = DOWNLOAD_STATUS_IDLE;
    LOG_INFO("取消下载任务: %d", task_id);
    
    // 清理任务
    free(task);
    g_tasks[task_index] = NULL;
    
    pthread_mutex_unlock(&g_tasks_mutex);
    return DOWNLOAD_SUCCESS;
}

int download_get_task_status(int task_id, download_task_t *task)
{
    pthread_mutex_lock(&g_tasks_mutex);
    
    if (!g_is_initialized) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载模块未初始化");
        return DOWNLOAD_ERROR_INIT;
    }
    
    // 查找任务
    download_task_t *target_task = NULL;
    for (int i = 0; i < MAX_DOWNLOAD_TASKS; i++) {
        if (g_tasks[i] && g_tasks[i]->task_id == task_id) {
            target_task = g_tasks[i];
            break;
        }
    }
    
    if (!target_task) {
        pthread_mutex_unlock(&g_tasks_mutex);
        LOG_ERROR("下载任务不存在: %d", task_id);
        return DOWNLOAD_ERROR_FILE;
    }
    
    if (task) {
        memcpy(task, target_task, sizeof(download_task_t));
    }
    
    pthread_mutex_unlock(&g_tasks_mutex);
    return DOWNLOAD_SUCCESS;
}

void download_register_progress_callback(download_progress_cb callback, void *user_data)
{
    pthread_mutex_lock(&g_tasks_mutex);
    g_progress_callback = callback;
    g_callback_user_data = user_data;
    pthread_mutex_unlock(&g_tasks_mutex);
}